package com.ys.web.ali.manager;

import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.ys.utils.alipay.config.YsAlipayConfig;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.web.app.service.YsAlipayConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @Author: dhf
 * @ClassName: YsAlipayConfigManager
 * @Date: 2023/2/22 13:08
 * @Description:
 * @Version: 1.0
 */
@Service
@Slf4j
public class YsAlipayConfigManager implements Runnable{
    @Autowired
    private YsAlipayConfigService ysAlipayConfigService;

    private static Map<String, DefaultAlipayClient> defaultAlipayClient = new HashMap<>();

    private static List<YsAlipayConfig> AlList = new ArrayList<>();

    @PostConstruct
    public void init () {
        new Thread(this).start();
    }
    @Override
    public void run() {
        while (true) {
            try {
                this.load();
                Thread.sleep(5*60*1000);
            } catch (Exception e) {
                Logger.error("YsAlipayConfigManager",  e);
            }
        }
    }


    private void load() {
        Logger.info("YsAlipayConfigManager---------------begin");
        List<YsAlipayConfig> list = new ArrayList<>();
        if(!Logger.isOnline()){
            Logger.info("YsAlipayConfigManager---------------本地环境");
            YsAlipayConfig ysAlipayConfig = new YsAlipayConfig();
            ysAlipayConfig.privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCVF+ZfYu1ALnL4T2RjhScIIXkgm0F8D63wF9zPB6WMJjwzjtv9ZG/A7eo1qLldX/Gx0ex/SEe2SsLSBXp2JvcDMjfkGrNqD7kgTjZlE6jBYvnr+QIq8obRNtMb/knoKvX6qosohMe6JvJIuRC8OD26TLyXRWsmLIbe9aT77UF29ytxoPCQwTibBKWd7MnuPbFSkJaxawnvaPWp3MMbUfwJUtePolaTd7Ka8hBUTnmI8+Oq1OtIxzia1jpEmpEqchMf+ouNM2QgTVAz/C6uEjgxmrzhZ7bEkS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5t2CQtNOzlpqO5xSmfXO+6Mwu5CifkliU1hnJHAhMgwQKBgArttBFttJOJ4zkyC7GZwgsUB4h8fumnl94h1vk1m1VgCS1N+qkeNXGfZKI243j+aIcLnviQuiBLjNj4pVeufu02MvPsw4Lj6nE3SIBqOvC4hmGfFdimAMRuuXyoAzf36U6ZpbKmcheLsyr8/8JrCUeLUbYLGGsOyZvcbBlh1K1k";
            ysAlipayConfig.appCpkCrt = "D:\\\\appCertPublicKey_2021003187690103.crt";
            ysAlipayConfig.appId = "2021003187690103";
            ysAlipayConfig.appRcCrt = "D:\\\\alipayRootCert.crt";
            ysAlipayConfig.aliCpkCrt = "D:\\\\alipayCertPublicKey_RSA2.crt";
//            ysAlipayConfig.privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZJUqTrv8e6Pbjr45KGAa5t+a8G0f8khR+P/hSO374TeU2pbGXMftd37bCQdQUaLuAn3qk26rU3rezF0fGStEPssASIhkuLMzwJ2vP2T/PNsJ/xqTictGDS14F09nApHkXIzea6MR24Pw2Wur3nMZaNiSHnkW3/bbtZ8Z0nJkRmeF4EPqYku0QhlfSKQRTdQt97p596kJav7Ry5fM/1Cohp1EAG16c0vXw+ShPUD5HE5uo8eJITrZC19EQIKNmSRA+v8aXR70QmsQZ3nSv7mUllT6yOineKQnW1G50dcs7N4bNOJkKRb8nsH7511FShNnkxOXtO6Ty9eP7MeeDiMNJAgMBAAECggEAY3oPqUKAwUk+JcOBP6u/op9MJ1/pMKyK1z8iQ/gVj6C5hPe4FagHyYBprGEqK1+ke/Ybqj5uBvvsg05Z9vneNr47eQvhI1dCf7R7mXVat3SwfmM/8z/1y70HA+4KgdHUPi1IDz2ncDjQW1ZPTivtw+drbxRl4Q/S5P8Fr/WQkBdFBepYdaTO0eHpgDsc3Ffsknj0r5L0IsH5GvqUZZyuqxDSGVrf5TPcAyMINUJff/t5IZcVzJ8i+Y/WLm1ic/T5DS5TfWJdY9su3JT39q0OqJRy1VrCGduuV+UAiuexQ/OdUyx6o28eJ9zMtabngflz3J54VuOdAFxciQkNbg2LyQKBgQD/PTuXM7dxBrLT58lyQCrr6wCE13UWdBKOl8uZsBfx5IJQLXz6h/lu1eOCl8JY/4n3DeAKnDrVkkql5p/UxcDAv7X26Er0yt+J+gsuTnEf7LBKl/TGU9VFAbNnje2TABXyD2J8WNA2iLH6hCby4RFyEYWNMjGLyiPjbpbLNPUyRwKBgQCZmic+U3hpzQk+plTcGzkKBMt9p1NpqalWCAO6+BCsYB9znywczrhlvHjQ4YzI2EqynHCDOwo45K9HiGaYLwXSIqL/kNYDipV7MXI8XT/mO7O6wgR+OaAtQXNKbAuRdpnC+0jmujp7ez5Un+grGwd8bWw5/invYH+P3pwzxwkV7wKBgQC8WYlh+M4D4DeS3Fbxspx5379QSFalLR6Mj0O1tBbXcBMh649wqWrN+ZScSDUoy9oZr+mGqudXt07Swi9sKkolctNq0tyNbDAtd5FMqKIeNuGZCi2dNTwKYkjrv/ZzJfsL14KL1FZCB/mermq3jJL9JCTznvik+ZQmPvOUHQ5b/QKBgFNQLLb+mVJxtvD3URHt5htMDH/EMVcfgky6niNch9ancIfLLycU7Smpd7J8lFsgDiwg9FoJvPqs93GKR3OGFdcrmFOcYKidE4U1hau+PHmJqmvC7qL0aLADTyBvyDqHJNGAcMNNAYmWiHFoJoqy53WS+F/gPyiqo6YKbZkb/Q6bAoGAYbJEInsnPno981/DTTGrT19XNsXDVD89Wl38XtYL4LI+oGNt5c79WckydKyWd1gGfeoo9/KsccCZKL4QMhYHwC3BEOs29rB8VoX0BGTT8rF98VIGcOF6RG3MrB1nyc0u0kpJCFxMYVLDbK7GMby1VluAf2C8/DO1vhHGb61813w=";
//            ysAlipayConfig.appCpkCrt = "E:\\\\appCertPublicKey_2021003184688936.crt";
//            ysAlipayConfig.appId = "2021003184688936";
//            ysAlipayConfig.appRcCrt = "E:\\\\alipayRootCert.crt";
//            ysAlipayConfig.aliCpkCrt = "E:\\\\alipayCertPublicKey_RSA2.crt";
            ysAlipayConfig.minPercentage = 0;
            ysAlipayConfig.maxPercentage = 100;
            ysAlipayConfig.minWithPercentage = 0;
            ysAlipayConfig.maxWithPercentage = 100;
            list.add(ysAlipayConfig);
        }else{
            list = ysAlipayConfigService.getList();
        }
        AlList = list;
        if (StringHandler.isNotEmpty(list) && list.size()>0) {
            Map<String, DefaultAlipayClient> map = new HashMap<>();
            for (YsAlipayConfig ysAlipayConfig : list) {
                //加载支付宝商户列表
                try {
                    if(StringHandler.isEmpty(ysAlipayConfig.appCpkCrt)){
                        log.info(ysAlipayConfig.appId+":app.cpk.crt文件不存在");
                        continue;
                    }
                    CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
                    certAlipayRequest.setAppId(ysAlipayConfig.appId);
                    certAlipayRequest.setFormat("JSON");
                    certAlipayRequest.setCharset("UTF-8");
                    certAlipayRequest.setSignType("RSA2");
                    certAlipayRequest.setPrivateKey(ysAlipayConfig.privateKey);
                    certAlipayRequest.setCertPath(ysAlipayConfig.appCpkCrt);
                    certAlipayRequest.setRootCertPath(ysAlipayConfig.appRcCrt);
                    certAlipayRequest.setAlipayPublicCertPath(ysAlipayConfig.aliCpkCrt);
                    certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                    map.put(ysAlipayConfig.appId, new DefaultAlipayClient(certAlipayRequest));
                } catch (Exception e) {
                    log.error("YsAlipayConfigManager------------加载错误",e);
                }
            }
            defaultAlipayClient = map;
        }
        Logger.info("YsAlipayConfigManager---------------end");
    }

    /**
     * @作者: dhf
     * @名称: 充值获取appid
     * @param
     * @时间: 2023/3/7 20:40
     * @备注:
     * @返回值: java.lang.String
     */
    public YsAlipayConfig getAppId(){
        if(StringHandler.isEmpty(AlList) && AlList.size()<0)
            return null;
        Random rd=new Random();  //创建实例
        int num=rd.nextInt(100)+1;
        YsAlipayConfig obj = null;
        for (YsAlipayConfig ysAlipayConfig : AlList) {
            if(ysAlipayConfig.minPercentage<=num && num<ysAlipayConfig.maxPercentage){
                obj = ysAlipayConfig;
                break;
            }
        }
        if(StringHandler.isEmpty(obj)){
            return null;
        }
        return obj;
    }

    /**
     * @作者: dhf
     * @名称: 提现获取appid
     * @param
     * @时间: 2023/3/7 20:40
     * @备注:
     * @返回值: java.lang.String
     */
    public YsAlipayConfig getAppIdWith(){
        if(StringHandler.isEmpty(AlList) && AlList.size()<0)
            return null;
        Random rd=new Random();  //创建实例
        int num=rd.nextInt(100)+1;
        YsAlipayConfig obj = null;
        for (YsAlipayConfig ysAlipayConfig : AlList) {
            if(ysAlipayConfig.minWithPercentage<=num && num<ysAlipayConfig.maxWithPercentage){
                obj = ysAlipayConfig;
                break;
            }
        }
        if(StringHandler.isEmpty(obj)){
            return null;
        }
        return obj;
    }
    public DefaultAlipayClient getDefaultAlipayClient(String appId){
        if(StringHandler.isEmpty(defaultAlipayClient))
            return null;
        return defaultAlipayClient.get(appId);
    }
    public YsAlipayConfig ysAlipayConfig(String appId){
        YsAlipayConfig returnobj= null;
        if(StringHandler.isEmpty(AlList))
            return null;
        for (YsAlipayConfig ysAlipayConfig : AlList) {
            if(ysAlipayConfig.appId.equals(appId)){
                returnobj = ysAlipayConfig;
                break;
            }
        }
        return returnobj;
    }

}
